# day8简单的KMeans聚类 
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans

def kmeans_clustering_demo(n_clusters=2, random_state=0):
    """
    简单KMeans聚类及可视化案例
    """
    # 构造数据
    X = np.array([[1, 2], [1, 4], [1, 0], [4, 2], [4, 4], [4, 0]])
    print("原始数据:\n", X)

    # KMeans聚类
    kmeans = KMeans(n_clusters=n_clusters, random_state=random_state)
    kmeans.fit(X)
    labels = kmeans.labels_
    centers = kmeans.cluster_centers_

    print("聚类标签:", labels)
    print("聚类中心:\n", centers)

    # 可视化
    plt.figure(figsize=(7, 5))
    scatter = plt.scatter(X[:, 0], X[:, 1], c=labels, cmap='viridis', s=100, edgecolor='k', label='数据点')
    plt.scatter(centers[:, 0], centers[:, 1], c='red', marker='X', s=200, label='聚类中心')
    plt.title(f'KMeans聚类演示 (n_clusters={n_clusters})')
    plt.xlabel('X坐标')
    plt.ylabel('Y坐标')
    plt.legend()
    plt.grid(True)
    plt.tight_layout()
    plt.show()

if __name__ == "__main__":
    kmeans_clustering_demo(n_clusters=2, random_state=42) 

    


